import sys
import pyautogui
from PySide6.QtWidgets import (QApplication, QWidget, QPushButton, QVBoxLayout, 
                               QHBoxLayout, QLabel, QToolTip, QGridLayout)
from PySide6.QtCore import Qt, QTimer, QPoint
from PySide6.QtGui import QFont, QFontDatabase

class FloatCopyPasteTool(QWidget):
    def __init__(self):
        super().__init__()
        # 核心状态变量
        self.is_paused = False  # 暂停状态
        self.current_opacity = 0.8  # 默认透明度80%
        
        # 初始化配置
        self.init_font()
        self.init_window()
        
        # 倒计时配置（缩短至1秒=1000ms，分2步）
        self.countdown_total = 1000  # 总时长1秒
        self.countdown_step = 500    # 每步500ms
        self.countdown_steps = self.countdown_total // self.countdown_step  # 2步
        
        # 状态变量
        self.dragging = False
        self.drag_start_pos = QPoint()
        self.copy_remaining = self.countdown_steps
        self.paste_remaining = self.countdown_steps
        
        # 定时器
        self.copy_timer = QTimer(self)
        self.paste_timer = QTimer(self)
        self.copy_timer.setInterval(self.countdown_step)
        self.paste_timer.setInterval(self.countdown_step)
        
        # 初始化UI
        self.init_ui()
        # 绑定事件
        self.bind_events()

    def init_font(self):
        """确保中文显示正常"""
        font_families = QFontDatabase.families()
        if "SimHei" in font_families:
            self.font = QFont("SimHei", 12)  # 字体放大
        else:
            self.font = QFont("WenQuanYi Micro Hei", 12)

    def init_window(self):
        """初始化窗口基础配置"""
        self.setWindowTitle("悬浮复制粘贴助手")
        self.setFixedSize(300, 320)  # 窗口放大至300×320
        self.setWindowFlags(
            Qt.FramelessWindowHint | 
            Qt.WindowStaysOnTopHint | 
            Qt.Tool
        )
        self.setWindowOpacity(self.current_opacity)  # 设置初始透明度
        self.move_to_top_right()

    def init_ui(self):
        # 主布局（垂直布局）
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(15)
        
        # 标题标签
        title_label = QLabel("复制粘贴助手", self)
        title_label.setAlignment(Qt.AlignCenter)
        title_font = QFont(self.font.family(), 14, QFont.Bold)  # 标题放大
        title_label.setFont(title_font)
        title_label.setStyleSheet("color: #333;")
        main_layout.addWidget(title_label)
        
        # 功能按钮容器（超大按钮区域）
        func_container = QWidget(self)
        func_container.setStyleSheet("background-color: rgba(255, 255, 255, 0.95); border-radius: 10px;")
        func_layout = QHBoxLayout(func_container)
        func_layout.setContentsMargins(10, 10, 10, 10)
        func_layout.setSpacing(10)
        
        # 复制按钮（超大尺寸）
        self.copy_btn = QPushButton("复制\n(Ctrl+C)", self)
        self.init_button_style(
            self.copy_btn, 
            normal_color="#4CAF50", 
            hover_color="#388E3C"
        )
        self.copy_btn.setMinimumHeight(120)  # 高度放大至120px
        func_layout.addWidget(self.copy_btn)
        
        # 粘贴按钮（超大尺寸）
        self.paste_btn = QPushButton("粘贴\n(Ctrl+V)", self)
        self.init_button_style(
            self.paste_btn, 
            normal_color="#2196F3", 
            hover_color="#1976D2"
        )
        self.paste_btn.setMinimumHeight(120)  # 高度放大至120px
        func_layout.addWidget(self.paste_btn)
        
        main_layout.addWidget(func_container)
        
        # 控制区域（包含暂停/关闭和透明度调节）
        control_container = QWidget(self)
        control_container.setStyleSheet("background-color: rgba(255, 255, 255, 0.95); border-radius: 10px;")
        control_layout = QVBoxLayout(control_container)
        control_layout.setContentsMargins(10, 8, 10, 8)
        control_layout.setSpacing(8)
        
        # 第一行：暂停/关闭按钮
        ctrl_btn_layout = QHBoxLayout()
        ctrl_btn_layout.setSpacing(10)
        
        # 暂停/继续按钮
        self.pause_btn = QPushButton("暂停", self)
        self.init_button_style(
            self.pause_btn, 
            normal_color="#FFC107", 
            hover_color="#FFA000"
        )
        self.pause_btn.setMinimumHeight(40)  # 控制按钮加高
        ctrl_btn_layout.addWidget(self.pause_btn)
        
        # 关闭按钮
        self.close_btn = QPushButton("关闭", self)
        self.init_button_style(
            self.close_btn, 
            normal_color="#F44336", 
            hover_color="#D32F2F"
        )
        self.close_btn.setMinimumHeight(40)
        ctrl_btn_layout.addWidget(self.close_btn)
        
        control_layout.addLayout(ctrl_btn_layout)
        
        # 第二行：透明度调节（新增）
        opacity_label = QLabel("透明度调节：", self)
        opacity_label.setFont(self.font)
        opacity_label.setStyleSheet("color: #555;")
        
        opacity_layout = QHBoxLayout()
        opacity_layout.setSpacing(8)
        opacity_layout.addWidget(opacity_label)
        
        # 50%透明度按钮
        self.opacity_50_btn = QPushButton("50%", self)
        self.init_opacity_button_style(self.opacity_50_btn, 0.5)
        opacity_layout.addWidget(self.opacity_50_btn)
        
        # 60%透明度按钮
        self.opacity_60_btn = QPushButton("60%", self)
        self.init_opacity_button_style(self.opacity_60_btn, 0.6)
        opacity_layout.addWidget(self.opacity_60_btn)
        
        # 80%透明度按钮
        self.opacity_80_btn = QPushButton("80%", self)
        self.init_opacity_button_style(self.opacity_80_btn, 0.8)
        opacity_layout.addWidget(self.opacity_80_btn)
        
        control_layout.addLayout(opacity_layout)
        
        main_layout.addWidget(control_container)

    def init_button_style(self, btn, normal_color, hover_color):
        """初始化功能按钮样式"""
        btn.setFont(QFont(self.font.family(), 14, QFont.Bold))  # 按钮字体放大
        btn.setStyleSheet(f"""
            QPushButton {{
                background-color: {normal_color};
                color: white;
                border-radius: 8px;
                padding: 8px;
            }}
            QPushButton:hover {{
                background-color: {hover_color};
            }}
            QPushButton:pressed {{
                background-color: {hover_color};
            }}
            QPushButton:disabled {{
                background-color: #BDBDBD;
                color: #757575;
            }}
        """)

    def init_opacity_button_style(self, btn, opacity):
        """初始化透明度按钮样式"""
        btn.setFont(QFont(self.font.family(), 10, QFont.Bold))
        btn.setMinimumHeight(30)
        # 当前选中透明度按钮高亮
        is_selected = (self.current_opacity == opacity)
        selected_style = "border: 2px solid #FF9800;" if is_selected else ""
        btn.setStyleSheet(f"""
            QPushButton {{
                background-color: #E0E0E0;
                color: #333;
                border-radius: 5px;
                padding: 3px;
                {selected_style}
            }}
            QPushButton:hover {{
                background-color: #BBDEFB;
            }}
        """)

    def move_to_top_right(self):
        """移动到右上角"""
        screen_geometry = QApplication.primaryScreen().geometry()
        x = screen_geometry.width() - self.width() - 20  # 右侧留20px
        y = 50  # 顶部留50px
        self.move(x, y)

    def bind_events(self):
        """绑定所有事件"""
        # 定时器信号
        self.copy_timer.timeout.connect(self.update_copy_countdown)
        self.paste_timer.timeout.connect(self.update_paste_countdown)
        
        # 功能按钮事件
        self.copy_btn.clicked.connect(self.trigger_copy)
        self.paste_btn.clicked.connect(self.trigger_paste)
        self.copy_btn.enterEvent = self.on_copy_enter
        self.copy_btn.leaveEvent = self.on_copy_leave
        self.paste_btn.enterEvent = self.on_paste_enter
        self.paste_btn.leaveEvent = self.on_paste_leave
        
        # 控制按钮事件
        self.pause_btn.clicked.connect(self.toggle_pause)
        self.close_btn.clicked.connect(self.close_program)
        
        # 透明度调节事件（新增）
        self.opacity_50_btn.clicked.connect(lambda: self.set_opacity(0.5))
        self.opacity_60_btn.clicked.connect(lambda: self.set_opacity(0.6))
        self.opacity_80_btn.clicked.connect(lambda: self.set_opacity(0.8))

    # 透明度调节功能（新增）
    def set_opacity(self, opacity):
        self.current_opacity = opacity
        self.setWindowOpacity(opacity)
        # 更新按钮选中状态
        self.init_opacity_button_style(self.opacity_50_btn, 0.5)
        self.init_opacity_button_style(self.opacity_60_btn, 0.6)
        self.init_opacity_button_style(self.opacity_80_btn, 0.8)
        self.show_tip(f"透明度设为 {int(opacity*100)}%")

    # 暂停/继续功能
    def toggle_pause(self):
        if not self.is_paused:
            # 进入暂停状态
            self.is_paused = True
            self.pause_btn.setText("继续")
            self.copy_timer.stop()
            self.paste_timer.stop()
            self.copy_btn.setEnabled(False)
            self.paste_btn.setEnabled(False)
            self.copy_btn.setText("复制\n(已暂停)")
            self.paste_btn.setText("粘贴\n(已暂停)")
            self.show_tip("已暂停操作")
        else:
            # 恢复运行状态
            self.is_paused = False
            self.pause_btn.setText("暂停")
            self.copy_btn.setEnabled(True)
            self.paste_btn.setEnabled(True)
            self.copy_btn.setText("复制\n(Ctrl+C)")
            self.paste_btn.setText("粘贴\n(Ctrl+V)")
            self.show_tip("已恢复操作")

    # 关闭程序功能
    def close_program(self):
        self.show_tip("程序已关闭")
        QTimer.singleShot(500, self.close)

    # 功能按钮事件处理
    def on_copy_enter(self, event):
        if not self.is_paused:
            self.copy_remaining = self.countdown_steps
            self.update_button_text(self.copy_btn, "复制")
            self.copy_timer.start()
        super().enterEvent(event)

    def on_copy_leave(self, event):
        self.copy_timer.stop()
        if not self.is_paused:
            self.copy_btn.setText("复制\n(Ctrl+C)")
        super().leaveEvent(event)

    def on_paste_enter(self, event):
        if not self.is_paused:
            self.paste_remaining = self.countdown_steps
            self.update_button_text(self.paste_btn, "粘贴")
            self.paste_timer.start()
        super().enterEvent(event)

    def on_paste_leave(self, event):
        self.paste_timer.stop()
        if not self.is_paused:
            self.paste_btn.setText("粘贴\n(Ctrl+V)")
        super().leaveEvent(event)

    # 倒计时更新（1秒分2步：0.5s→完成）
    def update_copy_countdown(self):
        if self.is_paused:
            return
        self.copy_remaining -= 1
        if self.copy_remaining <= 0:
            self.copy_timer.stop()
            self.trigger_copy()
            self.copy_btn.setText("复制\n(Ctrl+C)")
        else:
            self.update_button_text(self.copy_btn, "复制")

    def update_paste_countdown(self):
        if self.is_paused:
            return
        self.paste_remaining -= 1
        if self.paste_remaining <= 0:
            self.paste_timer.stop()
            self.trigger_paste()
            self.paste_btn.setText("粘贴\n(Ctrl+V)")
        else:
            self.update_button_text(self.paste_btn, "粘贴")

    def update_button_text(self, btn, action):
        remaining_sec = (self.copy_remaining if btn == self.copy_btn else self.paste_remaining) * self.countdown_step / 1000
        btn.setText(f"{action}\n{remaining_sec:.1f}s")

    # 复制粘贴核心功能
    def trigger_copy(self):
        if self.is_paused:
            return
        try:
            pyautogui.hotkey('ctrl', 'c')
            self.show_tip("复制成功")
        except Exception as e:
            self.show_tip(f"复制失败: {str(e)}")

    def trigger_paste(self):
        if self.is_paused:
            return
        try:
            pyautogui.hotkey('ctrl', 'v')
            self.show_tip("粘贴成功")
        except Exception as e:
            self.show_tip(f"粘贴失败: {str(e)}")

    def show_tip(self, text):
        tip_pos = self.mapToGlobal(QPoint(self.width()//2, self.height()))
        QToolTip.showText(tip_pos, text, self, None, 1500)

    # 窗口拖动
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.dragging = True
            self.drag_start_pos = event.globalPos() - self.frameGeometry().topLeft()
            event.accept()
        elif event.button() == Qt.RightButton:
            self.close_program()

    def mouseMoveEvent(self, event):
        if self.dragging and event.buttons() & Qt.LeftButton:
            self.move(event.globalPos() - self.drag_start_pos)
            event.accept()

    def mouseReleaseEvent(self, event):
        self.dragging = False

if __name__ == "__main__":
    app = QApplication(sys.argv)
    tool = FloatCopyPasteTool()
    tool.show()
    sys.exit(app.exec())